package com.zc.zby.basicframedemo.viewholder;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.zc.zby.basicframedemo.R;
import com.zc.zby.basicframedemo.model.ProgressModel;
import com.zc.zby.basicframedemo.utils.ToolUtil;

import static com.zc.zby.basicframedemo.utils.ToolUtil.getWindowWidth;

public class ProgressViewHolder extends BaseViewHolder<ProgressModel> {

    private ContentLoadingProgressBar mProgressBar;
    private TextView mTvLabelTop;
    private LinearLayout mLayoutLabelTop, mLayoutLabelTop2;
    private TextView mTvValue;
    private int mUpdateValue;

    public ProgressViewHolder(View itemView) {
        super(itemView);
        mProgressBar = $(R.id.progressBar);
        mTvLabelTop = $(R.id.tv_label_top);
        mLayoutLabelTop = $(R.id.layout_label_top);
        mLayoutLabelTop2 = $(R.id.layout_label_top2);
        mTvValue = $(R.id.tv_value);
    }

    @Override
    public void setData(ProgressModel data) {
        super.setData(data);
        startAnimation(getContext(), data.currentValue);
    }

    private void startAnimation(Context context, int maxValue) {
        AnimatorSet animatorSet = new AnimatorSet();  //组合动画
        int endValue = (getWindowWidth(context) - ToolUtil.dip2px(context, 82)) * maxValue / 100;
        ObjectAnimator progressAnimator = ObjectAnimator.ofInt(mProgressBar, "progress", 0, maxValue);
        ObjectAnimator translationX = new ObjectAnimator().ofFloat(mLayoutLabelTop, "translationX", 0, endValue);
        animatorSet.playTogether(progressAnimator, translationX);
        animatorSet.setDuration(1000);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        animatorSet.start();
        progressAnimator.addUpdateListener(valueAnimator -> {
            mUpdateValue = (int) valueAnimator.getAnimatedValue();
            mTvValue.setText("365亿（" + mUpdateValue + "%）");
        });
        progressAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (mUpdateValue == 100) {
                    mLayoutLabelTop.setVisibility(View.GONE);
                    mLayoutLabelTop2.setVisibility(View.VISIBLE);
                } else {
                    mLayoutLabelTop.setVisibility(View.VISIBLE);
                    mLayoutLabelTop2.setVisibility(View.GONE);
                }
            }
        });
    }
}
